package com.region.http.client.utils;

import com.region.common.adapter.logging.LoggerAdapter;
import com.region.common.adapter.logging.LoggerAdapterFactory;

import java.io.*;

/**
 * File and Stream Utils
 */
public class IOUtils {

    private static final LoggerAdapter logger = LoggerAdapterFactory.getLogger(IOUtils.class);

    /**
     * Converts a byte array to a file
     * @param path
     * @param bytes
     */
    public static File writeToFileByBytes(String path, byte[] bytes) {
        File file = new File(path);
        try (OutputStream outputStream = new FileOutputStream(file);) {
            if (!file.exists()) {
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                file.createNewFile();

            }
            outputStream.write(bytes);
            outputStream.flush();
            return file;
        } catch (IOException e) {
            logger.error("IOUtils write bytes error", e);
            return null;
        }
    }
    /**
     * Converts input stream to a file
     * @param path
     * @param inputStream
     */
    public static File writeToFileByInputStream(String path, InputStream inputStream) {
        File file = new File(path);
        try (OutputStream outputStream = new FileOutputStream(file);) {
            if (!file.exists()) {
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                file.createNewFile();
            }
            outputStream.write(convertInputStreamToBytes(inputStream));
            outputStream.flush();
            return file;
        } catch (IOException e) {
            logger.error("IOUtils write bytes error", e);
            return null;
        }
    }

    /**
     * Converts input stream to byte array
     *
     * @param inputStream
     * @return
     */
    public static byte[] convertInputStreamToBytes(InputStream inputStream) {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();) {
            byte[] bytes = new byte[64];
            while (inputStream.read(bytes) != -1) {
                outputStream.write(bytes);
            }
            return outputStream.toByteArray();
        } catch (Exception e) {
            logger.error("IOUtils convert bytes error", e);
            return null;
        }
    }
}
